package com.xiaomazi.acl.service.impl;

import com.xiaomazi.acl.entity.Role;
import com.xiaomazi.acl.entity.User;
import com.xiaomazi.acl.service.IndexService;
import com.xiaomazi.acl.service.PermissionService;
import com.xiaomazi.acl.service.RoleService;
import com.xiaomazi.acl.service.UserService;
import com.xiaomazi.common.utils.R;
import com.xiaomazi.security.entity.SecurityUser;
import com.xiaomazi.security.utils.JwtUtil;
import com.xiaomazi.servicebase.exception.LLXYException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @program: llxy-parent
 * @description: 基础业务类
 * @author: 小马子
 * @create: 2023-03-14 12:54
 **/
@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;


    /**
     * 根据token获取用户信息
     * @param name username
     * @return map
     */
    @Override
    public Map<String, Object> getUserInfo(String name) {
        Map<String,Object> result = new HashMap<>();
        User user = userService.selectByUsername(name);
        if (ObjectUtils.isEmpty(user)){
            throw new LLXYException(20001,"该用户不存在");
        }

        List<String> roleList = roleService.selectRoleByUserId(user.getId());
        if (roleList.isEmpty()){
            //前端框架必须返回一个角色，否则报错，如果没有角色，返回一个空角色
            roleList.add("");
        }

        //根据用户id获取操作权限值
        List<String> permissions = permissionService.selectPermissionValueByUserId(user.getId());
        result.put("name", user.getUsername());
        result.put("avatar", user.getSalt());
        result.put("roles", roleList);
        result.put("permissionValueList", permissions);

        return result;
    }

    /**
     * 根据用户名获取权限列表
     * @param name
     * @return
     */
    @Override
    public List<String> getMenu(String name) {
        return permissionService.selectPermissionValueByUserId
                (userService.selectByUsername(name).getId());
    }
}
